/*
Copyright (c) 2007, Arturo José Guédez Romero

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Cultusoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.cultusoft.groovin.plugins.selenium;

import com.cultusoft.groovin.log.GroovinLogger
import com.cultusoft.groovin.plugins.build.ProjectDependencyDownloader
import com.cultusoft.groovin.plugins.project.LibraryProject
import com.cultusoft.groovin.plugins.build.ProjectClasspathCreator
import com.cultusoft.groovin.configuration.Configuration

class SeleniumServerStarter {

    def logger = new GroovinLogger(this)
    
    def neededPackages = [new LibraryProject(group:"org/openqa/selenium/server", id:"selenium-server-coreless", version:"0.9.2"),
                            new LibraryProject(group:"org/openqa/selenium/core", id:"selenium-core", version:"0.8.3"),
                            new LibraryProject(group:"org/mortbay/jetty", id:"org.mortbay.jetty", version:"5.1.12"),
                            new LibraryProject(group:"tomcat", id:"servlet-api", version:"5.5.23"),
                            new LibraryProject(group:"ant", id:"ant", version:"1.6"),
                            new LibraryProject(group:"commons-logging", id:"commons-logging", version:"1.1.1")] as List

    def hostname = "localhost"
    def port = 4444
    def reportFolderName = "selenium"
    def logFileName ="startup.log"

	
 	public void run() {
        downloadNeededPackages()
        logger.log("Starting Selenium ...")
 		startSeleniumServer()
		waitForSeleniumToStart()
 		logger.log("Selenium has started")
 	}
 	
 	def waitForSeleniumToStart() {
       if (!isSeleniumRunning(true)) {
           throw new Exception("Selenium server did not start on given time")
       }	
 	}
    
 	private void startSeleniumServer() {
        if (isSeleniumRunning(false)) {
            return
        }
        
        def classpath = new ProjectClasspathCreator().createSimpleClasspath(neededPackages)

        def reportFolder = new File(new Configuration().reportFolder, reportFolderName)
        if (!reportFolder.exists()) {
            reportFolder.mkdirs()
        }

        def logFile = new File(reportFolder, logFileName).getPath()

        logger.log "Startup logs are saved in $logFile"


        logger.debug "running java call: java -cp $classpath org.openqa.selenium.server.SeleniumServer -Dselenium.log=$logFile"

        new AntBuilder().java(
                    classname:"org.openqa.selenium.server.SeleniumServer",
                    classpath:classpath,
                    fork:true,
                    spawn:true,
                    
                )   {
               sysproperty(key:"selenium.log", value:"$logFile")
        }

    }

    private boolean isSeleniumRunning(boolean retry) {
        InetAddress addr = InetAddress.getByName(hostname);
        SocketAddress socketAddress = new InetSocketAddress(addr, port);
        
        for (i in 1..10) {
            def isSeleniumAlive = openSocketClient(socketAddress, 2000)
            if (isSeleniumAlive) {
               return true
            } else {
                if (!retry) {
                    return false
                }
                logger.log("Selenium not alive")
                logger.log("Trying again in 2 seconds (" + (11-i) + " attempts left)")
                logger.log( "------------------------------------------------------------------------")
                Thread.sleep(2000)
            }
        }
        
        return false
    }
    
    def openSocketClient(def socketAddress, def timeoutMs) {
        try {
            Socket sock = new Socket();
            sock.connect(socketAddress, timeoutMs);
            sock.close()
            return true;
        } catch (Exception e) {}
        
        return false
    }

    def downloadNeededPackages() {
          new ProjectDependencyDownloader().downloadLibraries(neededPackages)
    }
}
